package org.bud.db.dynamic.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.bud.db.dynamic.anna.DS;
import org.bud.db.dynamic.base.DynamicDataSourceHolder;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @author shaun
 * @date 2025/4/1
 * @instruction
 */
@Aspect
@Order(1)
public class DynamicDatasourceAspect {

    @Pointcut("@annotation(org.bud.db.dynamic.anna.DS)")
    public void pointcut(){

    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint){
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        Method method = signature.getMethod();
        try {
            DS methodAnna = method.getAnnotation(DS.class);
            if(Objects.nonNull(methodAnna)){
                DynamicDataSourceHolder.setDS(methodAnna.value());
            }
            return joinPoint.proceed();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        } finally {
            DynamicDataSourceHolder.clear();
        }
    }
}
